import {AfterViewInit, Component, OnInit, ViewChild} from "@angular/core";
import {Util} from "../../../common/util";
import {ActivatedRoute} from "@angular/router";
import {TransferInstructionOptionService} from "./transfer-instructionOption.service";
import {PaginationModel} from "../../../widgets/pagination/pagination.component";
import {Observable} from "rxjs/Observable";

import * as _ from 'lodash';

@Component({
  templateUrl: './transfer-instructionOption.component.html',
  styleUrls: ['./transfer-instructionOption.component.scss']
})

export class TransferInstructionOptionComponent implements OnInit, AfterViewInit {

  public $ = window["$"];

  // 当前模态框类型 update/更新，add/新增
  public type = "add";

  // 当前托管行
  public nowBank: any = {
    BankName: "",
    vcBankId: ""
  };

  // 当前参数配置模态框内数据变量
  public commonModalData: any = {};

  // 模态框更新变量对象,用与修改更新或新建参数配置
  public commonModalUpdateData: any = {
    pmkyNum: "",
    vcBankId: "",
    vcFundCode: "",
    vcFundName: "",
    paymentMethod: "",
    vcFaxId: "",
    note: "",
    vcBusinessType: "",
    toSendTradeOrder: ""
  };

  // 右侧指令参数列表查询条件数据
  public searchBody: any = {
    bankName: '',
    vcFundCode: '',
    vcFundName: '',
    vcBusinessType: ''
  };

  // 请求返回的托管行列表
  public bankData: any = [];

  // 左侧托管行查询银行名称
  public searchBank: any = "";

  // 左侧托管行查询后返回的数据对象
  public searchBankData: any = [];

  // 二级模态框银行下拉数据
  public modalSelectBankData:any = [];

  // 二级模态框（基金选择列表）的查询条件对象
  public modalFundSearch: any = {
    vcBankId: "",
    vcBusinessType: "",    // 前两个属性由一级模态框传递
    fundCode: "",
    fundName: ""
  };

  // 二级模态框（基金选择列表）请求返回的基金数据对象
  public modalFundData: any;

  // 二级模态框（基金选择列表）内选中数据对象
  public checkedData = {
    fundCode: '',
    fundName: ''
  };

  // 发送方式
  public paymentMethod = {
    '1': '深圳通',
    '2': '网银',
    '3': '传真',
    '4': '电子'
  };

  // 业务类型
  public vcBusinessType = {
    '1': '银行间业务',
    '2': '新股网下申购',
    '3': '定存',
    '4': '债券分销',
    '5': '期货出入金',
    '6': 'QDII换汇',
    '7': '席位佣金支付',
    '8': '审计费'
  };

  // 分页数据模型
  public pageInfo: PaginationModel = {
    currentPageNum: 1,
    pageSize: 10,
    totalPages: 1,
    total: 0,
    pagesShow: 5,
    startRow: 0,
    endRow: 0,
    pageList: [5, 10, 25, 50, 100]
  };

  constructor(public service: TransferInstructionOptionService) {

  }

  ngOnInit() {
    // 页面首次加载
    this.search();
    this.service.getBankList({bankName:""}).subscribe(result => {
      if (result != null) {
        this.searchBankData = result;
        this.modalSelectBankData = result;
      }
    });
  }

  ngAfterViewInit(): void {
    //  调用时间插件
    Util.daterangepickerPluginInit(".daterangepicker-plugin");
    Util.datepickerPluginInit(".daterangepicker-single");
  }

  public search() {
    return this.getListData(this.wrapperSearchModule());
  }


  public resetSearch() {
    this.searchBody = {
      bankName: '',
      vcFundCode: '',
      vcFundName: '',
      vcBusinessType: ''
    };
  }

  /**
   * 获取划款指令参数配置列表数据
   * @param {any} param 查询参数
   * @param {number} [currentPageNum=this.pageInfo.currentPageNum]
   * @param {number} [pageSize=this.pageInfo.pageSize]
   * @returns
   * @memberof TransferInstructionOptionComponent
   */
  public getListData(param, currentPageNum: number = this.pageInfo.currentPageNum,
                     pageSize: number = this.pageInfo.pageSize) {
    return this.service.getListData(param, currentPageNum, pageSize).subscribe(result => {
      if (result != null && result.data != null && result.data.list != null) {
        this.bankData = [];
        this.bankData = result.data.list;
        this.pageInfo.totalPages = result.data.pages;
        this.pageInfo.total = result.data.total;
        this.pageInfo.startRow = result.data.startRow;
        this.pageInfo.endRow = result.data.endRow;
      }
    });

  }

  public wrapperSearchModule() {
    const param = this.$.extend(true, {}, this.searchBody);
    return param;
  }

  /**
   * 获取银行列表
   * @param {any} bankName 银行名称
   * @param {any} listSearch 是否点击列表查询,如果为true则查询符合bankName的参数配置列表
   * @param {any} item 如果是列表查询而且非查询全部，则传入当前点击行的数据
   * @returns
   * @memberof TransferInstructionOptionComponent
   */
  public getBankListData(bankName, listSearch?, item?) {
    const param = {
      bankName: bankName
    };
    if (listSearch) {
      this.nowBank.BankName = bankName;
      if (bankName === "") {
        this.nowBank.vcBankId = "";
      }
      if (item) {
        this.nowBank.vcBankId = item.vcBankId;
      }
      return this.getListData({bankName: bankName});
    }
    return this.service.getBankList(param).subscribe(result => {
      if (result != null) {
        this.searchBankData = result;
      }
    });
  }

  public openModal(type, item?) {
    this.type = type;
    if (type === "update") {
      this.commonModalData = this.$.extend(true, {}, item);
    }
    if (type === "add") {
      this.commonModalData = {};
      this.commonModalData.BankName = this.nowBank.BankName;
      this.commonModalData.vcBankId = this.nowBank.vcBankId;
    }
    this.$("#commonModal").modal('show');
  }

  /**
   * 删除配置
   * @param item 点击当前行数据
   */
  public deleteFundConfig(item) {
    const that = this;
    window["swal"]({
        title: "提示",
        text: "是否要删除基金配置？",
        type: "info",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        closeOnConfirm: false,
        closeOnCancel: true,
        showLoaderOnConfirm: true
      },
      function (isConfirm) {
        if (isConfirm) { // 确认
          const param = {
            pmkyNumList: item.pmkyNum
          };
          return that.service.deleteFundConfig(param).subscribe(result => {
            if (result) {
              window["swal"]("提示", `删除成功`, "success");
              that.search();
            }
          });
        } else { // 取消
          // window["swal"]("Cancelled", "Your imaginary file is safe :)", "error");
        }
      });
  }

  public addOrUpateFundConfig() {
    const that = this;
    if (this.type === "update") {
      window["swal"]({
          title: "提示",
          text: "是否要更新基金配置？",
          type: "info",
          showCancelButton: true,
          confirmButtonColor: "#DD6B55",
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          closeOnConfirm: false,
          closeOnCancel: true,
          showLoaderOnConfirm: true
        },
        function (isConfirm) {
          if (isConfirm) { // 确认
            const param = that.copyData(that.commonModalData, that.commonModalUpdateData);
            that.service.addORUpdateFundConfig(param, that.type).subscribe(data => {
              if (data) {
                window["swal"]("更新成功", "", "success");
                that.search();
              }
            });
          } else { // 取消
            // window["swal"]("Cancelled", "Your imaginary file is safe :)", "error");
          }
        });

    } else {
      window["swal"]({
          title: "",
          text: "是否确定要新增基金配置信息?",
          type: "info",
          showCancelButton: true,
          confirmButtonColor: "#DD6B55",
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          closeOnConfirm: false,
          closeOnCancel: true,
          showLoaderOnConfirm: true
        },
        function (isConfirm) {
          if (isConfirm) { // 确认
            const param = that.copyData(that.commonModalData, that.commonModalUpdateData);
            that.service.addORUpdateFundConfig(param, that.type).subscribe(data => {
              if (data) {
                window["swal"]("新增成功", "", "success");
                that.search();
              }
            });
          } else { // 取消
            // window["swal"]("Cancelled", "Your imaginary file is safe :)", "error");
          }
        });

    }
  }

  // 拷贝相同属性
  // @param p 目标变量
  // @param c 变量模板
  public copyData(p, c) {
    for (let i in p) {
      for (let a in c)
        if (i === a) {
          c[a] = p[i];
        }
    }
    return c;
  }

  // 打开二级模态框并查询
  public openChooseFundModal(item) {
    if(item.vcBankId&&item.vcBusinessType){
      this.modalFundSearch.vcBankId = item.vcBankId;
      this.modalFundSearch.vcBusinessType = item.vcBusinessType;
      this.searchFundList(item);
      this.$("#chooseFundModal").modal('show');
    }
    else{
      window["swal"]("提示", "请选择托管行和业务类型再进行选择基金代码操作", "info");
    }
  }

  // 切换选中状态
  checked(item, $event) {
    if ($event.target.checked) {
      this.checkedData = {
        fundCode: item.vcFundCode,
        fundName: item.vcFundName
      };
    }
  }

  // 二级模态框查询函数
  public searchFundList(item?) {
    var param = {
      vcBankId: this.modalFundSearch.vcBankId,
      vcBusinessType: this.modalFundSearch.vcBusinessType,
      fundCode: this.modalFundSearch.vcFundCode ? this.modalFundSearch.vcFundCode : '',
      fundName: this.modalFundSearch.vcFundName ? this.modalFundSearch.vcFundName : '',
      pageSize: 10000,
      page: 1
    };
    this.service.searchFundList(param).subscribe(result => {
      if (result != null) {
        this.modalFundData = result.list;
      }
    });
  }

  // 二级模态框确定按钮，将选择的基金返回到上一级模态框中
  public confirmFund() {
    this.commonModalData.vcFundCode = this.checkedData.fundCode;
    this.commonModalData.vcFundName = this.checkedData.fundName;
    this.$("#chooseFundModal").modal('hide');
  }

  // 二级模态框关闭，并清空数据
  public closeFundModal() {
    this.modalFundSearch = {
      vcBankId: "",
      vcBusinessType: "",
      fundCode: "",
      fundName: ""
    };
    this.$("#chooseFundModal").modal('hide');
  }

  /**
   * 根据页码请求查询相关配置列表数据,如果当前活动页码就是目标页码，则不进行任何查询
   * 直接返回
   * @param {currentPageNum}
   */
  public pageNavigation(currentPageNum: number) {
    this.pageInfo.currentPageNum = currentPageNum;
    this.search();
  }

  /**
   * 改变每页显示记录数
   * @param {pageSize}
   */
  public pageSizeChange(pageSize: number) {
    if (pageSize !== this.pageInfo.pageSize) {
      this.pageInfo.pageSize = pageSize;
      this.pageInfo.currentPageNum = 1;
      this.search();
    }
  }
}
